# from fastapi.exceptions import HTTPException
# 官方推荐注册异常处理器时，建议 Starlette 的 HTTPException
from starlette.exceptions import HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi import status

async def global_http_exception_handler(request, exc):
    """全局HTTP异常处理函数"""
    print(exc, type(exc), dir(exc))
    if exc.status_code == 500:
        err_msg = 'Server Internal Error'
    else:
        err_msg = exc.detail

    return JSONResponse({
        'code': exc.status_code,
        'err_msg': err_msg,
        'status': 'Failed'
    })


async def global_validation_exception_handler(request, exc):
    """全局校验异常处理函数"""
    return JSONResponse({
        'code': status.HTTP_422_UNPROCESSABLE_ENTITY,
        'err_msg': exc.errors()[0],
        'status': 'Failed'
    })